package com.shiro.demo.controller;

import com.shiro.demo.domain.User;
import com.shiro.demo.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/shiro")
public class ShiroController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserService userService;

    @RequestMapping("/index")
    public String index(){
        logger.info("go index");
        return "index";
    }

    @RequestMapping("/login")
    public String login(){
        logger.info("go login");
        return "login";
    }
    @RequestMapping("/add")
    public String add(){
        logger.info("go add");
        return "add";
    }
    @RequestMapping("/update")
    public String update(){
        logger.info("go update");
        return "update";
    }

    @RequestMapping(value = "/loginAction",method = RequestMethod.POST)
    public String loginAction(@RequestParam("name") String name, @RequestParam("password") String password){
        logger.info("go loginAction");
        Map<String,String> map = new HashMap<>();
        UsernamePasswordToken token = new UsernamePasswordToken(name,password.toCharArray());
        try {
            //将用户的登陆交给shiro去验证，登陆失败就重定向到登录页
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
           logger.error("login failed,exception is {}",e.getMessage());
            return "redirect:/shiro/login";
        }
        //验证通过后，更新最近登陆时间
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        user.setLastLoginTime(new Date());
        userService.updateUser(user);
        return "redirect:/shiro/userInfo";
    }

    @RequestMapping(value = "/userInfo")
    public String userInfo(ModelMap modelMap){
        //通过验证后，可以直接取到user对象
        User user = (User)SecurityUtils.getSubject().getPrincipal();
        modelMap.put("user",user);
        return "userInfo";
    }

    /**
     * shiro直接退出登陆
     */
    @RequestMapping(value="logout")
    public String logout(){
        try {
            SecurityUtils.getSubject().logout();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return "redirect:/shiro/index";
    }

}
